package com.liumin.demo.comlink

import android.os.Bundle
import android.util.Log
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.liumin.comlink.http.RetrofitUtil
import com.liumin.comlink.http.rx.RxObservableSchedulers
import com.liumin.demo.comlink.base.ErrorHandlerObservable
import com.liumin.demo.databinding.ActivityTestHttpBinding
import com.liumin.publiclib.helper.JSONHelper
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable

class TestHttpActivity : AppCompatActivity() {
    private val TAG = "TestHttpActivity"
    private val url = "http://xx.xx.xx.34x:xx/"
    private val urlGit = "https://api.github.com/"
    private var resultTv:TextView? = null
    private var mCompositeDisposable: CompositeDisposable = CompositeDisposable()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = ActivityTestHttpBinding.inflate(layoutInflater)
        setContentView(binding.root)
        initView(binding)
    }

    private fun initView(binding:ActivityTestHttpBinding){
        RetrofitUtil.setBaseUrl(urlGit)
        resultTv = binding.testHttpResultTv
        binding.testHttpLoadDataObservableBtn.setOnClickListener {
            val subscribe = RetrofitUtil.init().create(HttpService::class.java)
                .login("CSFLC", "010203", "Android", "123456789")
                .compose(RxObservableSchedulers.rxSchedulerHelper())
                .compose(ErrorHandlerObservable.handleResult())
                .subscribe(
                    { userBaseResponse ->
                        resultTv?.text = JSONHelper.toJsonString(
                            userBaseResponse
                        )
                    }, { throwable ->
                        run {
                            resultTv?.text = throwable.message
                            Log.i(TAG, JSONHelper.toJsonString(throwable))
                        }
                    }
                )
            addSubscribe(subscribe)
        }
    }

    /**
     * 添加订阅
     */
    private fun addSubscribe(subscription: Disposable?) {
        if (mCompositeDisposable == null) {
            mCompositeDisposable = CompositeDisposable()
        }
        if (subscription != null) {
            mCompositeDisposable.add(subscription)
        }
    }

    /**
     * 取消订阅
     */
    private fun unSubscribe() {
        if (mCompositeDisposable != null) {
            mCompositeDisposable.clear()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unSubscribe()
    }

}